//
//  HMSportCaptureViewController.m
//  HMBest22
//
//  Created by Apple on 17/1/16.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "HMSportCaptureViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#define HMSportMaskAnimationDuration 0.25
@interface HMSportCaptureViewController ()
// 快门界面的约束
@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *layoutConstraints;
/// 运动的距离
@property (weak, nonatomic) IBOutlet UILabel *sportDictanceLabel;
/// 运动的水印图片
@property (weak, nonatomic) IBOutlet UIImageView *waterPrintImageView;

/// 预览界面
@property (weak, nonatomic) IBOutlet UIView *preview;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;

// 输入设备  -->摄像头
@property (nonatomic, strong) AVCaptureDeviceInput *deviceInput;
// 输出设备  -->输出的是照片
@property (nonatomic, strong) AVCaptureStillImageOutput *output;
// 会话 -->核心对象   -->连接输入和输出设备
@property (nonatomic, strong) AVCaptureSession *session;
// 预览的图层  -->取景框
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *previewLayer;
// 拍摄按钮
@property (weak, nonatomic) IBOutlet UIButton *captureBtn;
// 摄像头切换按钮
@property (weak, nonatomic) IBOutlet UIButton *rotateBtn;
/// 拍摄的图片
@property (nonatomic, strong) UIImage *captureImage;
@end

@implementation HMSportCaptureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpSession];
}

- (void)setUpSession
{
    // 1.创建输入设备
    // 1.1获取摄像头的输入设备  -->摄像头有两个  前置和后置
    AVCaptureDevice *device = [self captureDevice];

    self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    // 2.获取输出设备
    self.output = [[AVCaptureStillImageOutput alloc] init];
    
    // 3.创建会话 -->连接输入和输出设备
    self.session = [[AVCaptureSession alloc] init];
    // 添加输入和输出设备
    if ([self.session canAddInput:self.deviceInput]) {
        [self.session addInput:self.deviceInput];
    }
    
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    
    // 4.创建预览图层 -->取景框
    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer = previewLayer;
    // 4.1设置大小
    CGRect rect = [UIScreen mainScreen].bounds;
    rect.size.height -= 126;
    self.previewLayer.frame = rect;
    // 4.2插入到图层的最底层
    [self.view.layer insertSublayer:previewLayer atIndex:0];
    // 设置填充模式
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    // 5.开启会话
    [self startSession];
}

// 开启会话
- (void)startSession
{
    [self.session startRunning];
}
// 停止会话
- (void)stopSession
{
    [self.session stopRunning];
}
/// 是否隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

// 开始拍照
- (IBAction)startCapture
{
    if (!self.session.isRunning) {
        [self transitionView];
        return;
    }
    // 开启快门
    [self maskViewWithClose:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HMSportMaskAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 结束快门
        [self maskViewWithClose:NO];
    });
    
    // 获取图片和保存图片
    [self saveImage];
}

- (void)saveImage
{
    // AVCaptureConnection :摄像头和照片的连接
    
    // 1.获取图片
    [self.output captureStillImageAsynchronouslyFromConnection:self.output.connections.firstObject completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
            return ;
        }
        
        // 获取照片的二进制数据
        NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        // 转换成图片
        UIImage *image = [UIImage imageWithData:data];
        
        // 获取预览视图的宽高
        CGRect rect = self.preview.bounds;
        // 开启图形上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
        // 画图片
        [image drawInRect:CGRectInset(rect, 0, -(self.view.bounds.size.height - rect.size.height) * 0.5)];
        // 画水印图片
        [self.waterPrintImageView.image drawInRect:_waterPrintImageView.frame];
        // 画运动距离的文字
        [self.sportDictanceLabel.attributedText drawInRect:_sportDictanceLabel.frame];
        // 获取最新的图片
        UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
        // 关闭图形上下文
        UIGraphicsEndImageContext();
        
        
        // 2.保存图片到用户的相册
        UIImageWriteToSavedPhotosAlbum(finalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
    }];
}

/// 保存图片后调用
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    self.captureImage = image;
    // 停止界面
    [self stopSession];
    NSString *str = (error == nil) ? @"图片已保存成功" : @"保存失败";
    NSLog(@"%@",str);
    
    self.tipLabel.text = str;
    
    [UIView animateWithDuration:2.0 animations:^{
        self.tipLabel.alpha = 1;
    } completion:^(BOOL finished) {
        self.tipLabel.alpha = 0;
    }];
    
//    [UIView];
    
}
// 是否关闭快门
- (void)maskViewWithClose:(BOOL)close
{
    if (close) {// 禁用约束
        [NSLayoutConstraint deactivateConstraints:self.layoutConstraints];
    }else{// 激活约束
        [NSLayoutConstraint activateConstraints:self.layoutConstraints];
        // 翻转相关按钮 -->拍摄按钮   分享按钮
        [self transitionView];
    }
    
    // 添加动画
    [UIView animateWithDuration:HMSportMaskAnimationDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)transitionView
{
    // 当前拍摄按钮的标题是否为空
    BOOL isEmptyTitle = (self.captureBtn.currentTitle == nil);
    // 按钮的标题
    NSString *title = isEmptyTitle ? @"√" : nil;
    // 给按钮设置标题
    [self.captureBtn setTitle:title forState:UIControlStateNormal];
    
    // 翻转拍摄按钮
    
    // 动画的翻转样式
    UIViewAnimationOptions options = isEmptyTitle ? UIViewAnimationOptionTransitionFlipFromRight : UIViewAnimationOptionTransitionFlipFromLeft;
    // transitionWithView:需要执行动画的控件
    [UIView transitionWithView:self.captureBtn duration:HMSportMaskAnimationDuration options:options animations:nil completion:^(BOOL finished) {
        if (title == nil) {
            //  开启拍摄会话
            [self startSession];
        }
    }];
    
    
    // 翻转  切换摄像头/分享按钮
    // 根据拍摄按钮的标题设置图片
    NSString *imageName = isEmptyTitle ? @"ic_waterprint_share" : @"ic_waterprint_revolve";
    [self.rotateBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    
    [UIView transitionWithView:self.rotateBtn duration:HMSportMaskAnimationDuration options:options animations:nil completion:nil];
}

- (void)shareImage
{
    //1、创建分享参数
    NSArray* imageArray = @[self.captureImage];
    if (imageArray.count == 0) {
        return;
    }

        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                         images:imageArray
                                            url:nil
                                          title:@"分享标题"
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];
}
// 翻转摄像头
- (IBAction)rotateCamera
{
    if (!self.session.isRunning) {
        NSLog(@"应该去分享");
        [self shareImage];
        return;
    }
    // 获取翻转后的摄像头
    AVCaptureDevice *device = [self captureDevice];
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    // 从会话中删除摄像头
    [self.session removeInput:self.deviceInput];
    // 停止会话
    [self stopSession];
    // 将输入设备添加到会话   如果会话中有摄像头的输入设备 不能再进入新的摄像头设备  除非删除之前的摄像头设备
    if ([self.session canAddInput:deviceInput]) {
        [self.session addInput:deviceInput];
        // 开启会话
        [self startSession];
        self.deviceInput = deviceInput;
    }
    
    
}

/// 保证  默认是后置摄像头 点击时翻转
- (AVCaptureDevice *)captureDevice
{
    // 获取相机的位置
    AVCaptureDevicePosition position = (self.deviceInput.device.position != AVCaptureDevicePositionBack) ? AVCaptureDevicePositionBack : AVCaptureDevicePositionFront;
    
    // 获取输入设备数组
    NSArray *array = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    AVCaptureDevice *device;
    // 寻找对应的输入设备
    for (AVCaptureDevice *obj in array) {
        if (position == obj.position) {
            device = obj;
            break;
        }
    }
    
    return device;
}
- (IBAction)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
